<template>
  <div class="upload">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-errorimg :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 右上角的删除图标 -->
    <div v-if="value" class="del" @click="del">
      <i class="el-icon-circle-close" />
    </div>
    <!-- 图片预览图标 -->
    <div v-if="value" class="show_big" @click="isShow = true">
      <i class="el-icon-zoom-in" />
    </div>
    <!-- 图片预览容器 -->
    <el-dialog class="dialog" :visible.sync="isShow" title="图片预览">
      <img v-errorimg style="width: 100%" :src="value" alt="">
    </el-dialog>
    <!-- 进度条 -->
    <el-progress v-if="showProgress" :percentage="percentage" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDYv3xb092g5F9oEOIm6C3g6KK5dx3yf9O', // 身份识别 ID
  SecretKey: '4uVs1vc6LM9j5FCvSlqhJhzCBwTntlPp' // 身份密钥
})
export default {
  name: 'Upload',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      percentage: 0, // 进度条百分比
      showProgress: false, // 控制进度条是否显示
      isShow: false // 控制图片预览容器是否显示
    }
  },
  methods: {
    //  上传前执行的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 自定义上传方式，腾讯云上传执行函数
    httpRequest(res) {
      // 让进度条显示
      this.showProgress = true
      // 每次上传进度都从0开始
      this.percentage = 0
      // console.log(file)
      const file = res.file
      cos.putObject(
        {
          Bucket: 'hr-1310832771' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: 'STANDARD', // 固定参数不用修改
          Body: file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度条显示
            // console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
            // 判断进度条达到百分之百
            if (progressData.percent === 1) {
              // 设置定时器,让进度条不立马消失
              setTimeout(() => {
                // 设置进度条消失
                this.showProgress = false
              }, 1000)
            }
          }
        },
        (err, data) => {
          // 上传成功的回调，err:如果有错误就显示err  没有就显示data
          //   this.value = 'http://' + data.Location
          //   console.log(this.value)
          this.$emit('input', 'http://' + data.Location)
          //   console.log(err || data)
        }
      )
    },

    // 删除按钮点击事件
    del() {
      this.$emit('input', '')
    }
  }
}
</script>

<style scoped lang="scss">
.upload {
  position: relative;
  display: inline-block;
  .del {
    position: absolute;
    top: 6px;
    right: 6px;
    color: red;
    display: none;
  }
  .show_big {
    position: absolute;
    top: 6px;
    right: 25px;
    color: red;
    display: none;
  }
  &:hover {
    .del,
    .show_big {
      display: inline-block;
    }
  }
}
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
